package com.bestdata.TD440.datahandle.service;

import cn.hutool.setting.Setting;
import com.alibaba.fastjson.JSONObject;
import com.bestdata.TD440.emNewModel.NewMessageSend;
import com.bestdata.TD440.emNewModel.model.DrsModelPOJO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.bestdata.TD440.datahandle.model.Map.dMap;

/**
 * @author
 */

@Service
@Lazy(false)
@EnableScheduling
@Configuration
public class Timmer{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String hid;

    private static String sn;

    private HashMap<String ,String> devMap = new HashMap();

    @Scheduled(cron = "0 */1 * * * ?")
    public void getMaxValue() {

        logger.info("Quartz is beginning....");

        if(dMap.size() > 0){

            LinkedHashMap<String,String> dataMap = new LinkedHashMap<>();

            HashMap<String,Object> cloneMap = new HashMap<>();

            //此处cloneMap的理由是设备采集测值持续向dMap中添加，只为取出同一时间两只设备测值
            cloneMap = dMap;

            DrsModelPOJO drsModelPOJO = new DrsModelPOJO();
            drsModelPOJO.setSn(sn);
            drsModelPOJO.setHid(hid);
            drsModelPOJO.setTm(System.currentTimeMillis()+"");

            for (Map.Entry<String, Object> entry : cloneMap.entrySet()) {
                //获取设备序列号
                String devInfo = devMap.get(entry.getKey());

                logger.info(devInfo+"{}{}{}{}");
                String value = "0";
                if("0001".equals(devInfo)){
                    value = (Double.parseDouble(entry.getValue().toString())/0.00279393)+"";
                }else{
                    value = (Double.parseDouble(entry.getValue().toString())/0.00285258)+"";
                }

                dataMap.put("01"+devInfo+"0ZHD",value.substring(0,9));

            }

            drsModelPOJO.setData(dataMap);

            /**
             *   2020年9月27日16:21:57 发现并解决问题：当高频率数据接收时，从map中取值并发送
             *   会触发Unexpected error occurred in scheduled task异常，解决方案：定时器内部
             *   创建线程，并调用转发服务，若不创建线程可能导致数据重复发送等问题
             */
            new Thread(new Runnable() {
                @Override
                public void run() {
                    logger.info("new Message Send To DRS ,DataPOJO  --->  {}"+drsModelPOJO);
                    try {
                        NewMessageSend.newMessageSendCore(JSONObject.toJSONString(drsModelPOJO));
                    } catch (Exception e) {
                        logger.error("new Message Send To DRS false !!!!!!!!!!!!!!!"+e);
                        e.printStackTrace();
                    }finally {
                        dMap.clear();
                    }
                }
            }).start();
        }
    }


    @Value("${data.hid}")
    public void setHid(String hid) {
        Timmer.hid=hid;
    }

    @Value("${data.sns}")
    public void setSns(String sn) {
        if(sn.length() == 1){
            sn = "000"+sn;
        }else if(sn.length() == 2){
            sn = "00"+sn;
        }else if(sn.length() == 3){
            sn = "0"+sn;
        }
        Timmer.sn=sn;
    }

    @Value("${data.devid}")
    public void setDevId(String devid) {
        String[] devInfo = devid.split(",");

        for (String dev : devInfo) {

            String[] info = dev.split(":");
            devMap.put(info[0],info[1]);

        }
    }

}
